package com.djj.nanny.controller;

import com.djj.nanny.common.Result;
import com.wf.captcha.SpecCaptcha;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final String CAPTCHA_KEY = "captcha:";

    @GetMapping("/generate")
    public Result<Map<String, String>> generateCaptcha() {
        // 生成验证码
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        String verCode = specCaptcha.text().toLowerCase();
        String key = UUID.randomUUID().toString();
        
        // 存入redis并设置过期时间为2分钟
        stringRedisTemplate.opsForValue().set(CAPTCHA_KEY + key, verCode, 2, TimeUnit.MINUTES);
        
        // 将key和base64图片返回给前端
        Map<String, String> result = new HashMap<>();
        result.put("key", key);
        result.put("image", specCaptcha.toBase64());
        
        return Result.success(result);
    }
} 